package com.ocom.mqsimple.business.card;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ocom.common.request.payconfig.AddCardInfoVo;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.CommonUtil;
import com.ocom.common.vo.human.UserInfoYkmVo;
import com.ocom.common.vo.webapi.ImportCardVo;
import com.ocom.mqsimple.config.ProvideCardConfig;
import com.ocom.mqsimple.feign.HumanClientService;
import com.ocom.mqsimple.feign.PayConfigClientService;
import com.ocom.redis.util.RedisUtil;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Component
public class ProvideCardConsumerMqListener {

	private Logger logger = LoggerFactory.getLogger(ProvideCardConsumerMqListener.class);

	@Resource
	RedisUtil redisUtil;

	@Autowired
	private HumanClientService humanClientService;

	@Autowired
	private PayConfigClientService payConfigClientService;


	/**
	 * 把该监听命名为A监听
	 * 监听队列  远程服务支付接口发送消息  该队列会接受
	 * [message, headers, channel]
	 * @return {@link }
	 * @throws
	 */
	@RabbitListener(queues = ProvideCardConfig.PROVIDE_CARD_QUEUE)
	public void process(Message message, @Headers Map<String, Object> headers, Channel channel) throws Exception {
		logger.info("ProvideCard 消费中");
		logger.info("message【{}】",message);
		String humanMessage = new String(message.getBody(), StandardCharsets.UTF_8);
		//TODO 数据库操作样例
		logger.info("ProvideCard-start:【{}】",humanMessage);
		logger.info("System.currentTimeMillis()【{}】",System.currentTimeMillis());

		ImportCardVo importCardVo = JSON.parseObject(humanMessage, ImportCardVo.class);

		try {
			Map<String, Object> searchMap = new HashMap<>();
			searchMap.put("comId",importCardVo.getComId());
			if(importCardVo.getPId()!=null && importCardVo.getPId()>0l){
				searchMap.put("pId",importCardVo.getPId());
			}else{
				if(CommonUtil.isNull(importCardVo.getPCode())){
					throw new RuntimeException("人员和编号都为空");
				}
				searchMap.put("pName",importCardVo.getPName());
				searchMap.put("pCode",importCardVo.getPCode());
			}
			searchMap.put("page",1);
			searchMap.put("size",1);
			Result result = humanClientService.PersonnelGetPersonInfo(searchMap);
			if (result.getCode()!=200){
				/**
				 * 记录错误日志
				 */
				Map<String,Object> map=new HashMap<>();
				map.put("errMsg","查找异常");
				map.put("json",importCardVo);
				redisUtil.leftPush("ImportErr:detail:"+importCardVo.getComId()+":"+importCardVo.getTimestamp(),map,86400l);
			}
			String list = JSON.parseObject(JSON.toJSONString(result.getData())).get("list").toString();
			List<UserInfoYkmVo> userInfoYkmVos = JSON.parseArray(list, UserInfoYkmVo.class);
			if (userInfoYkmVos.size()>0) {
				UserInfoYkmVo userInfoYkmVo = userInfoYkmVos.get(0);

				AddCardInfoVo addCardInfoVo= new AddCardInfoVo();
				addCardInfoVo.setComId(importCardVo.getComId());
				addCardInfoVo.setAccountNo(importCardVo.getComId()+"P"+userInfoYkmVo.getPId());
				addCardInfoVo.setCardNo(importCardVo.getCardNo());
				addCardInfoVo.setDeposit(0l);
				addCardInfoVo.setEndDate(importCardVo.getEndDate());
				addCardInfoVo.setCostFee(0l);
				addCardInfoVo.setPId(userInfoYkmVo.getPId());
				addCardInfoVo.setDeptId(0l);
				addCardInfoVo.setAccTypeId(1l);
				addCardInfoVo.setUser("mq");

				try {
					Result result1 = payConfigClientService.GetXFAccount(importCardVo.getComId(),userInfoYkmVo.getPId().intValue());
					if(result1.getCode()==200 && result1.getData()!=null){
						JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(result1.getData()));
						addCardInfoVo.setAccTypeId(jsonObject.getInteger("accTypeId").longValue());
					}
				}catch (Exception exception){
					logger.info("发卡-获取消费账户类型报错 【{}】",exception);
				}
				Result result2 = payConfigClientService.AddCardInfo(addCardInfoVo);
				if(result2.getCode()!=200){
					Map<String,Object> map=new HashMap<>();
					map.put("errMsg",result2.getMsg());
					map.put("json",importCardVo);
					redisUtil.leftPush("ImportErr:detail:"+importCardVo.getComId()+":"+importCardVo.getTimestamp(),map,86400l);
				}
			}else{
				/**
				 * 记录错误日志
				 */
				Map<String,Object> map=new HashMap<>();
				map.put("errMsg","未找到人员");
				map.put("json",importCardVo);
				redisUtil.leftPush("ImportErr:detail:"+importCardVo.getComId()+":"+importCardVo.getTimestamp(),map,86400l);
			}
		} catch (Exception e) {
			logger.info("出现异常队列消息开始进入死信队列{{}}",e);
			Map<String,Object> map=new HashMap<>();
			map.put("errMsg","MQ处理异常："+e.getMessage());
			map.put("json",importCardVo);
			redisUtil.leftPush("ImportErr:detail:"+importCardVo.getComId()+":"+importCardVo.getTimestamp(),map,86400l);

		}

//		//存在
//		if(size==null || size==0l){
//			if(flag){
//				Map<String,Object> map1=new HashMap<>();
//				map1.put("key","ImportErr:detail:"+importCardVo.getComId()+":"+importCardVo.getTimestamp());
//				map1.put("type",1);
//				map1.put("name","卡号批量导入");
//				map1.put("timestamp",importCardVo.getTimestamp());
//				map1.put("datetime", DateUtil.getDateTime());
//				redisUtil.leftPush("ImportErr:"+importCardVo.getComId(),map1,3600l);
//			}
//		}

		channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
		logger.info("ProvideCard-end:【{}】",humanMessage);
		logger.info("System.currentTimeMillis()【{}】",System.currentTimeMillis());
	}

	/**
	 * 把该监听命名为B监听
	 * 监听死信队列  远程服务支付接口发送消息  该队列会接受
	 * [message, headers, channel]
	 * @return {@link }
	 * @throws
	 */
	@RabbitListener(queues =  ProvideCardConfig.PROVIDE_CARD_DIE_QUEUE)
	public void processForDie(Message message, @Headers Map<String, Object> headers, Channel channel) throws Exception {
		//死信队列放弃
		channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
		logger.info("发卡-死信队列放弃 ， 【{}】",message);
	}


}
